# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

library(optparse)
library(magrittr)
library(tidyverse)
library(gramm4R)
library(SummarizedExperiment)


option_list <- list(
  make_option("--i", default = "AllMet_Raw.txt", type = "character", help = "metabolite data file"),
  make_option("--g", default = "true_SampleInfo.csv", type = "character", help = "sample group file"),
  make_option("--mf", default = "mic_data.txt", type = "character", help = "metabolite data file"),
  make_option("--cf", default = "cov_data.txt", type = "character", help = "metabolite data file"),
  make_option("--config", default = "calculate_config.txt", type = "character", help = "config file")
)
opt <- parse_args(OptionParser(option_list = option_list))

args <- commandArgs(trailingOnly = F)
scriptPath <- dirname(sub("--file=", "", args[grep("--file", args)]))
source(str_c(scriptPath, "/base.R"))

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

configData <- read_tsv(opt$config, col_names = F) %>%
  set_colnames(c("arg", "value"))

corP <- configGet(configData, "p") %>%
  as.numeric()
cor <- configGet(configData, "coe") %>%
  as.numeric()
corMethod <- configGet(configData, "corMethod")
fdrMethod <- configGet(configData, "fdrMethod")
metaNor <- configGet(configData, "metaNor") %>%
  as.logical()
rarefaction <- configGet(configData, "rarefaction") %>%
  as.logical()
r <- configGet(configData, "r") %>%
  as.numeric()
alpha <- configGet(configData, "alpha") %>%
  as.numeric()

metData <- read_tsv(opt$i)
micData <- read_tsv(opt$mf)
res <- if (file.exists(opt$cf)) {
  covData <- read_tsv(opt$cf)
  print(covData)
  interIds <- Reduce(intersect, list(colnames(metData), colnames(micData), colnames(covData)))
  selectMetData <- metData %>%
    select(interIds)
  selectMicData <- micData %>%
    select(interIds)
  selectCovData <- covData %>%
    select(interIds)
  metMatrix <- selectMetData %>%
    select(-c("Metabolite")) %>%
    as.matrix()
  micMatrix <- selectMicData %>%
    select(-c("Metabolite")) %>%
    as.matrix()
  covMatrix <- selectCovData %>%
    select(-c("Metabolite")) %>%
    as.matrix()
  metSE <- SummarizedExperiment(assays = list(counts = metMatrix), rowData = selectMetData$Metabolite)
  micSE <- SummarizedExperiment(assays = list(counts = micMatrix), rowData = selectMicData$Metabolite)
  covSE <- SummarizedExperiment(assays = list(counts = covMatrix), rowData = selectCovData$Metabolite)
  Gramm(metSE, micSE, covSE, metaNor = metaNor, rarefaction = rarefaction, r = r, alpha = alpha)
}else {
  interIds <- intersect(colnames(metData), colnames(micData))
  selectMetData <- metData %>%
    select(interIds)
  selectMicData <- micData %>%
    select(interIds)
  metMatrix <- selectMetData %>%
    select(-c("Metabolite")) %>%
    as.matrix()
  micMatrix <- selectMicData %>%
    select(-c("Metabolite")) %>%
    as.matrix()
  metSE <- SummarizedExperiment(assays = list(counts = metMatrix), rowData = selectMetData$Metabolite)
  micSE <- SummarizedExperiment(assays = list(counts = micMatrix), rowData = selectMicData$Metabolite)
  Gramm(metSE, micSE, FALSE, metaNor = metaNor, rarefaction = rarefaction, r = r, alpha = alpha)
}


corData <- res$r
pData <- res$p
typeData <- res$type

corData.frame <- corData %>%
  as.table() %>%
  as.data.frame()

pData.frame <- pData %>%
  as.table() %>%
  as.data.frame()

allData <- tibble(Node1 = corData.frame$Var1, Node2 = corData.frame$Var2, r = corData.frame$Freq, P = pData.frame$Freq)

finalParent <- paste0("./")

edgeData <- allData %>%
  filter(P < corP & abs(r) > cor) %>%
  arrange(desc(abs(r))) %>%
  mutate(Node1 = as.character(Node1)) %>%
  mutate(Node2 = as.character(Node2))
write_csv(edgeData, paste0(finalParent, "/Network_Edges_for_Cytoscape.csv"))

nodes <- unique(c(edgeData$Node1, edgeData$Node2))
infoData <- tibble(Node = nodes) %>%
  mutate(Size = {
    Node %>%
      map_int(function(x) {
        edgeData %>%
          filter(Node1 == x | Node2 == x) %>%
          nrow()
      })
  })
write_csv(infoData, paste0(finalParent, "/Network_Nodes_for_Cytoscape.csv"))

corOutData <- corData %>%
  as.data.frame() %>%
  rownames_to_column(" ")
write_csv(corOutData, "Correlation_coefficients.csv")

pOutData <- pData %>%
  as.data.frame() %>%
  rownames_to_column(" ")

write_csv(pOutData, "Correlation_p_values.csv")

typeOutData <- typeData %>%
  as.data.frame() %>%
  rownames_to_column(" ")
write_csv(typeOutData, "Correlation_methods.csv")



